package com.ciwong.epaper.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.common.EVariableGlobal;
import com.ciwong.epaper.common.dialogbottom.CatalogBottomDialog;
import com.ciwong.epaper.common.dialogbottom.ChackGradeBottomDialog;
import com.ciwong.epaper.modules.bookstore.bean.PublishWorkContent;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.CatelogBean;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.adapter.NewBookDeskAdapter;
import com.ciwong.epaper.modules.me.bean.BookDeskBean;
import com.ciwong.epaper.modules.me.bean.BooksPage;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.EpaperInfoGradeNameBean;
import com.ciwong.epaper.modules.me.bean.FavoritesBook;
import com.ciwong.epaper.modules.me.bean.MaterialBean;
import com.ciwong.epaper.modules.me.bean.RefreshNewBookDesk;
import com.ciwong.epaper.modules.me.bean.SubjectBean;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.ViewUtil;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * Created by keepon on 2018/8/7.
 */
public class JiaoCaiTongBuItemView extends LinearLayout {
    private static final String TAG = "JiaoCaiTongBuItemView";
    private NewBookDeskAdapter mNewBookDeskAdapter;
    private TextView mTvTypeName;
    private RecyclerView mRecyclerView;
    private CatelogBean mBookDeskCatalogueBean = new CatelogBean();
    private List<SubjectBean> mSubjectBeanList = new ArrayList<>();
    private List<CatalogueInfo> mCataloguesBeanList = new ArrayList<>();
    private ArrayList<String> mVersionIdList = new ArrayList();
    private List<EpaperInfo.Server> mEpaperServerList = new ArrayList<>();


    private HashMap<String, CatalogueInfo> mShowingCatalogueInfos = new HashMap();
    private HashMap<String, CatalogueInfo> mReadyShowCatalogueInfos = new HashMap();
    private NewBookDeskAdapter.OnMaterItemClicklistener mOnMaterItemClicklistener;
    private ChackGradeBottomDialog chackGradeBottomDialog;
    private CatalogBottomDialog catalogBottomDialog;
    private Context mContext;
    private BookDeskBean mBookDeskBean;
    private List<EpaperInfoGradeNameBean> mEpaperInfoGradeNameBeans;
    private int JUMP_TO_WORK_CONTENT_CODE = 10009;

    public JiaoCaiTongBuItemView(Context context) {
        this(context, null);
        mContext = context;
    }

    public JiaoCaiTongBuItemView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public JiaoCaiTongBuItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(this.getContext()).inflate(R.layout.layout_kewaituozhan_item, this);
        init();
        initEvent();

    }


    private void init() {
        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_DESK_CATALOGUE, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                failed(data);
            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                try {
                    if (data != null) {
                        mBookDeskCatalogueBean = (CatelogBean) data;
                        updateCataloguesBeanLocal(mBookDeskCatalogueBean);

                    }
                } catch (Exception e) {

                }
            }
        });

        //mTvTypeName = findViewById(R.id.tv_type_name);
        mRecyclerView = findViewById(R.id.recycler_view);
        mRecyclerView.setFocusable(false);
        //mTvTypeName.setText("教材同步");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRecyclerView.addItemDecoration(new DividerItemDecorationLastHide(getContext(), LinearLayoutManager.VERTICAL, ViewUtil.dip2px(getContext(), (float) 0.5), R.color.def_line_color));

        mNewBookDeskAdapter = new NewBookDeskAdapter(getContext(), mSubjectBeanList, mCataloguesBeanList);
        mRecyclerView.setAdapter(mNewBookDeskAdapter);

        mNewBookDeskAdapter.setOnDialogCreatedListener(new NewBookDeskAdapter.OnDialogCreatedListener() {
            @Override
            public void onCreatedListener(Dialog dialog) {
                if (EVariableGlobal.CHECKED_FRAGMENT_BOOKDESK == true && dialog != null) {
                    EVariableGlobal.CHECKED_GUIDE_DIALOG_SHOWING = true;
                    dialog.show();
                }
            }
        });
        mOnMaterItemClicklistener = new NewBookDeskAdapter.OnMaterItemClicklistener() {
            @Override
            public void onClickChangeMoudle(final int mSubjectPosition, final SubjectBean subjectBean, final List<CatalogueInfo> cataloguesBean, String currentUnitBeanUnitid) {

                if (cataloguesBean == null) {
                    return;
                }
                if (!DoubleClickCheckUtils.vertify500Duration()) {
                    return;
                }
                try {
                    List<MaterialBean> materialBeanList = subjectBean.getMaterial();
                    MaterialBean mMaterialBean = getMaterialBean(materialBeanList);
                    BooksPage booksPage = mMaterialBean.getBooksPage();
                    catalogBottomDialog.initData(cataloguesBean, Integer.valueOf(cataloguesBean.get(mSubjectPosition).getId()), booksPage);
                    catalogBottomDialog.setOnItemCallBackListener(new CatalogBottomDialog.ItemCallBack() {
                        @Override
                        public void onItemCallBack(CatalogueInfo returnCatalogueInfo) {
                            try {
                                if (returnCatalogueInfo != null && returnCatalogueInfo.getChildren().size() > 0) {
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            CatalogueInfo retrunCatalogueBean = mCataloguesBeanList.get(mSubjectPosition);
                            List<CatalogueInfo> CatalogueInfoList = retrunCatalogueBean.getChildren();
                            setSelectedCataloguesUnitBean(CatalogueInfoList, returnCatalogueInfo);
                            setSelectedCataloguesUnit(returnCatalogueInfo);
                            mBookDeskCatalogueBean.setCatalogues(mCataloguesBeanList);
                            updateCataloguesAdapterAndSaveLocal();
                        }
                    });
                    catalogBottomDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onClickChangeMaterial(final int subjectPosition, SubjectBean subjectBean, List<CatalogueInfo> cataloguesBean, final MaterialBean selectedMaterialBean) {

                if (!DoubleClickCheckUtils.vertify500Duration()) {
                    return;
                }
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                    return;
                }
                try {

                    chackGradeBottomDialog.initData(subjectBean, mEpaperInfoGradeNameBeans);
                    chackGradeBottomDialog.setOnItemCallBackListener(new ChackGradeBottomDialog.ItemCallBack() {
                        @Override
                        public void onItemCallBack(List<MaterialBean> materialBeans, int position) {
                            if (materialBeans != null) {
                                MaterialBean materialBean = materialBeans.get(position);
                                if (materialBean.getVersionId() == selectedMaterialBean.getVersionId()) {
                                    return;
                                }
                                loadNetData(subjectPosition, true, materialBean, materialBean.getBooksPage().getPackageId(), materialBean.getBooksPage().getServiceId());
                            }
                        }
                    });
                    chackGradeBottomDialog.show();
                } catch (Exception e) {

                }

            }

            @Override
            public void onClickStartStudy(int position, SubjectBean subjectBean, List<CatalogueInfo> cataloguesBean, CatalogueInfo catalogueInfo) {
                if (!DoubleClickCheckUtils.vertify500Duration()) {
                    return;
                }


                try {
                    String mBookIds;
                    List<MaterialBean> materialBeanList = subjectBean.getMaterial();
                    mBookIds = getBookIds(materialBeanList);
                    MaterialBean mMaterialBean = getMaterialBean(materialBeanList);
                    String packAgeId = "";
                    String resourceName = "";
                    CatalogueInfo selectedCataloguesUnitBean = new CatalogueInfo();
                    List<CatalogueInfo> CatalogueInfoList = new ArrayList<>();
                    if (null != cataloguesBean) {
                        if (null != cataloguesBean.get(position).getChildren() && cataloguesBean.get(position).getChildren().size() > 0) {
                            CatalogueInfoList = cataloguesBean.get(position).getChildren();
                        } else {
                            CatalogueInfoList = cataloguesBean;
                        }

                        selectedCataloguesUnitBean = getSelectedCataloguesUnitBean(CatalogueInfoList);
                        if (selectedCataloguesUnitBean != null) {
                            packAgeId = selectedCataloguesUnitBean.getId();
                            resourceName = selectedCataloguesUnitBean.getName();
                        }
                    }
                    SubjectBean jumpSubjectBean = new SubjectBean();
                    if (null != mSubjectBeanList && mSubjectBeanList.size() > 0) {
                        jumpSubjectBean = mSubjectBeanList.get(0);
                    }
                    List<MaterialBean> material = jumpSubjectBean.getMaterial();
                    int workTag = 1;
                    MaterialBean materialBean = new MaterialBean();
                    for (int i = 0; i < material.size(); i++) {
                        if (material.get(i).isSelected()) {
                            materialBean = material.get(i);
                        }
                    }

                    int mServiceId = 0;
                    FavoritesBook mInfo = new FavoritesBook();
                    if (null != materialBean) {
                        BooksPage booksPage = materialBean.getBooksPage();
                        mInfo.setAppId(booksPage.getAppId());
                        mInfo.setBookIntro(booksPage.getBookIntro());
                        mInfo.setBookType(booksPage.getBookType());
                        mInfo.setCover(booksPage.getCover());
                        mInfo.setGrade(booksPage.getGrade());
                        mInfo.setSubject(booksPage.getSubject());
                        mInfo.setIsFree(booksPage.getIsFree());
                        mInfo.setPackageIsFree(booksPage.getPackageIsFree());
                        mInfo.setProductId(booksPage.getProductId());
                        if (!"".equals(booksPage.getPackageId())) {
                            mInfo.setPackageId(Integer.valueOf(booksPage.getPackageId()));
                        }
                        if (null != booksPage.getProductName()) {
                            mInfo.setProductName(booksPage.getProductName());
                        }
                        mInfo.setGradeName(booksPage.getGradeName());
                        mInfo.setRequired(booksPage.getRequired());
                        if (!"".equals(booksPage.getServiceId())) {
                            mServiceId = Integer.valueOf(booksPage.getServiceId());
                            mInfo.setServiceId(Integer.valueOf(booksPage.getServiceId()));
                        }
                        mInfo.setServiceName(booksPage.getServiceName());
                        mInfo.setBookType(booksPage.getBookType());
                        mInfo.setTeamId(booksPage.getTeamId());
                        mInfo.setTeamName(booksPage.getTeamName());
                        mInfo.setBookIntro(booksPage.getBookIntro());
                        mInfo.setSort(booksPage.getSort());
                        mInfo.setIsPwd(booksPage.getIsPwd());
                        mInfo.setPackageType(booksPage.getPackageType());
                    }
                    List<PublishWorkContent> workContents = new ArrayList<>();
                    EpaperJumpManager.jumpToTeaWorkContent(R.string.go_back, (Activity) mContext, RequestCode.TeaWorkContent.HOME_WORK, catalogueInfo, mServiceId, mInfo, mEpaperServerList, workTag, workContents, JUMP_TO_WORK_CONTENT_CODE);
//                    if (mMaterialBean.getIsExpire() == 1 || mMaterialBean.getIsFree() == 1) {
                    //EpaperJumpManager.jumpToNewBookContentFromDesk(R.string.go_back, (Activity) mContext, mBookIds, packAgeId, resourceName, true);
//                    } else {
//                        MeJumpManager.jumpBuyService((Activity) mContext, R.string.go_back, mMaterialBean.getServerId(), -1, 1, "");
//                    }
                } catch (Exception e) {

                }

            }


            @Override
            public void onClickRefreshCatalogue(int subjectPosition, SubjectBean subjectBean, List<CatalogueInfo> cataloguesBean) {
                if (mVersionIdList != null && mVersionIdList.size() > subjectPosition) {
                    //getBookDeskItemCatalogue(mVersionIdList.get(subjectPosition), subjectPosition, false, null);
                    //loadNetData();

                }
            }


        };
        mNewBookDeskAdapter.setOnMaterItemClicklistener(mOnMaterItemClicklistener);

        initDialogFragment();
    }

    private void initEvent() {

    }

    //从本地获取科目教材选中情况刷新到页面
    private void updateMaterialItemBeansLocal(List<SubjectBean> subjectBeanList) {
        if (subjectBeanList == null) {
            return;
        }
        mSubjectBeanList.clear();
        mSubjectBeanList.addAll(subjectBeanList);
        try {
            //获取本地记录科目的VersionId,放入集合mVersionIdList，首页请求失败，点击刷新时需要的参数
            for (SubjectBean subjectBean : subjectBeanList) {
                List<MaterialBean> localMaterialBeanList = subjectBean.getMaterial();
                if (localMaterialBeanList != null) {
                    for (MaterialBean localMaterialBean : localMaterialBeanList) {
                        if (localMaterialBean.isSelected()) {
                            mVersionIdList.add(localMaterialBean.getBooksPage().getPackageId());
                        }
                    }
                }
            }
        } catch (Exception e) {

        }

        //教材同步刷新
//        mNewBookDeskAdapter.updateSubjec
//		mNewBookDeskAdapter.updateData(mSubjectBeanList, mCataloguesBeanList);tBeanList(mSubjectBeanList);

    }

    //从本地获取单元选中情况刷新到页面
    private void updateCataloguesBeanLocal(CatelogBean bookDeskCatalogueBean) {
        if (bookDeskCatalogueBean == null) {
            return;
        }
        //List<CatalogueInfo> catelogBeans = new ArrayList<>();
        //catelogBeans.addAll(bookDeskCatalogueBean.getCatalogues());
        mCataloguesBeanList = bookDeskCatalogueBean.getCatalogues();
        if (mCataloguesBeanList != null) {
            setSelectedCataloguesUnitBeanLocal(mCataloguesBeanList);
//            mNewBookDeskAdapter.updateCatalogueList(mCataloguesBeanList);
            mNewBookDeskAdapter.updateData(mSubjectBeanList, mCataloguesBeanList);
        }
    }

    // //记录本地选中的单元
    private List<CatalogueInfo> setSelectedCataloguesUnitBeanLocal(List<CatalogueInfo> CatalogueInfoList) {
        try {
            if (CatalogueInfoList != null && CatalogueInfoList.size() > 0) {
                for (int i = 0; i < CatalogueInfoList.size(); i++) {
                    CatalogueInfo CatalogueInfo = CatalogueInfoList.get(i);
                    if (CatalogueInfo.getChildren() != null && CatalogueInfo.getChildren().size() > 0) {
                        CatalogueInfo.setChildren(setSelectedCataloguesUnitBeanLocal(CatalogueInfo.getChildren()));
                    } else {
                        if (CatalogueInfo.getSelect()) {
                            mShowingCatalogueInfos.put(CatalogueInfo.getId(), CatalogueInfo);
                        }
                    }
                }

            }
        } catch (Exception e) {

        }

        return CatalogueInfoList;
    }

    private void updateMaterialItemBeansFromNet(List<SubjectBean> subjectBeanList) {
        if (subjectBeanList == null) {
            return;
        }
        Clazz clazz = EApplication.getInstance().getClazz();
        if (clazz == null || clazz.getGradeId() == 0) {
            clazz = new Clazz();
            clazz.setGradeId(1107);
        }
        try {

            // mVersionIdList.clear();
            boolean isSelected = false;
            for (int m = 0; m < subjectBeanList.size(); m++) {
                SubjectBean netSubjectBean = subjectBeanList.get(m);
                isSelected = false;
                List<MaterialBean> netMaterialBeans = netSubjectBean.getMaterial();
                if (netMaterialBeans != null && netMaterialBeans.size() > 0) {
                    for (int i = 0; i < netMaterialBeans.size(); i++) {
                        MaterialBean netMaterialBean = netMaterialBeans.get(i);
                        out:
                        //把本地选中的记录赋值给新拉到的数据
                        /*for (SubjectBean localSubject : mSubjectBeanList) {
                            List<MaterialBean> localMaterialBeans = localSubject.getMaterial();
                            for (int j = 0; j < localMaterialBeans.size(); j++) {
                                if (localMaterialBeans.get(j).getVersionId() == netMaterialBean.getVersionId()) {
                                    if (localMaterialBeans.get(j).isSelected()) {
                                        isSelected = true;
                                        mVersionIdList.add(netMaterialBean.getBooksPage().getPackageId());
                                    }
                                    netMaterialBean.setSelected(localMaterialBeans.get(j).isSelected());
                                    break out;
                                }
                            }
                        }*/

                        for (int a = 0; a < mVersionIdList.size(); a++) {
                            if (mVersionIdList.get(a).equals(netMaterialBean.getBooksPage().getPackageId())) {
                                isSelected = true;
                                netMaterialBean.setSelected(isSelected);
                                break out;
                            }
                        }

                    }

                    //本地没有记录，根据班级默认选一个
                    if (!isSelected) {
                        for (int i = 0; i < netMaterialBeans.size(); i++) {
                            MaterialBean netMaterialBean = netMaterialBeans.get(i);
                            if (netMaterialBean.getGradeId() == clazz.getGradeId()) {
                                netMaterialBean.setSelected(true);
                                isSelected = true;
                                mVersionIdList.add(netMaterialBean.getBooksPage().getPackageId());
                                break;
                            }
                        }
                    }
                    //对应班级没有,默认选第一个
                    if (!isSelected) {
                        if (netMaterialBeans != null && netMaterialBeans.size() > 0) {
                            MaterialBean netMaterialBean = netMaterialBeans.get(0);
                            netMaterialBean.setSelected(true);
                            isSelected = true;
                            mVersionIdList.add(netMaterialBean.getBooksPage().getPackageId());
                        }
                    }
                }

            }
        } catch (Exception e) {

        }
        mSubjectBeanList.clear();
        mSubjectBeanList.addAll(subjectBeanList);
        //教材同步刷新
        updateSubjectBeanListAdapterAndSaveLocal();

    }

    //把本地选中的单元数据同步到新获取到的网络数据中
    private boolean synSelectedCatalogueInfo(List<CatalogueInfo> CatalogueInfoList) {
        try {
            for (int j = 0; j < CatalogueInfoList.size(); j++) {
                CatalogueInfo netCatalogueInfo = CatalogueInfoList.get(j);
                /*if (netCatalogueInfo != null) {
                    boolean b = synSelectedCatalogueInfo(netCatalogueInfo.getChildren());
                    if (b) {
                        return true;
                    }
                } else {*/
                for (int i = 0; i < mCataloguesBeanList.size(); i++) {
                    if (netCatalogueInfo.getId().equals(mCataloguesBeanList.get(i).getId()) && null != mCataloguesBeanList.get(i).getSelect() && mCataloguesBeanList.get(i).getSelect()) {
                        netCatalogueInfo.setSelect(true);
                        mReadyShowCatalogueInfos.put(netCatalogueInfo.getId(), netCatalogueInfo);
                        return true;
                    }
                }
                    /*Set<Map.Entry<String, CatalogueInfo>> entries = mShowingCatalogueInfos.entrySet();
                    for (Map.Entry<String, CatalogueInfo> showingCatalogueInfo : entries) {
                        if (showingCatalogueInfo.getKey().equals(netCatalogueInfo.getId()) && showingCatalogueInfo.getValue().getSelect()) {
                            netCatalogueInfo.setSelect(true);
                            mReadyShowCatalogueInfos.put(netCatalogueInfo.getId(), netCatalogueInfo);
                            return true;
                        }
                }*/
            }
        } catch (Exception e) {

        }
        return false;

    }

    //单个科目切换教材时，如果此时切回的教材是页面初始化后切换过的，单元的记录选中情况可以保持
    private boolean synSelectedItemCatalogueInfo(List<CatalogueInfo> CatalogueInfoList) {
        try {
            for (int j = 0; j < CatalogueInfoList.size(); j++) {
                CatalogueInfo netCatalogueInfo = CatalogueInfoList.get(j);
                if (netCatalogueInfo.getChildren() != null && netCatalogueInfo.getChildren().size() > 0) {
                    boolean b = synSelectedCatalogueInfo(netCatalogueInfo.getChildren());
                    if (b) {
                        return true;
                    }
                } else {

                    Set<Map.Entry<String, CatalogueInfo>> entries = mShowingCatalogueInfos.entrySet();
                    for (Map.Entry<String, CatalogueInfo> showingCatalogueInfo : entries) {
                        if (showingCatalogueInfo.getKey().equals(netCatalogueInfo.getId()) && showingCatalogueInfo.getValue().getSelect()) {
                            netCatalogueInfo.setSelect(true);
                            return true;
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return false;

    }

    private void setSelectedCataloguesUnit(CatalogueInfo returnCatalogueInfo) {
        try {
            if (mCataloguesBeanList != null && mCataloguesBeanList.size() > 0) {
                for (int i = 0; i < mCataloguesBeanList.size(); i++) {
                    CatalogueInfo catalogueInfo = mCataloguesBeanList.get(i);
                    if (catalogueInfo.getChildren() != null && catalogueInfo.getChildren().size() > 0) {
                        List<CatalogueInfo> childrenList = catalogueInfo.getChildren();
                        for (int j = 0; j < childrenList.size(); j++) {
                            CatalogueInfo childrenCatalogueInfo = childrenList.get(j);
                            if (childrenCatalogueInfo.getId().equals(returnCatalogueInfo.getId())) {
                                childrenCatalogueInfo.setSelect(true);
                                mShowingCatalogueInfos.put(childrenCatalogueInfo.getId(), childrenCatalogueInfo);
                            } else {
                                childrenCatalogueInfo.setSelect(false);
                                catalogueInfo.setSelect(false);
                                mShowingCatalogueInfos.remove(childrenCatalogueInfo.getId());
                            }
                        }
                    } else {
                        if (catalogueInfo.getId().equals(returnCatalogueInfo.getId())) {
                            catalogueInfo.setSelect(true);
                            mShowingCatalogueInfos.put(catalogueInfo.getId(), catalogueInfo);
                        } else {
                            catalogueInfo.setSelect(false);
                            mShowingCatalogueInfos.remove(catalogueInfo.getId());
                        }
                    }
                }

            }
        } catch (Exception e) {

        }
    }

    //设置选中的CataloguesUnitBean
    private List<CatalogueInfo> setSelectedCataloguesUnitBean(List<CatalogueInfo> CatalogueInfoList, CatalogueInfo returnCatalogueInfo) {
        try {
            if (CatalogueInfoList != null && CatalogueInfoList.size() > 0) {
                for (int i = 0; i < CatalogueInfoList.size(); i++) {
                    CatalogueInfo CatalogueInfo = CatalogueInfoList.get(i);
                    if (CatalogueInfo.getChildren() != null && CatalogueInfo.getChildren().size() > 0) {
                        CatalogueInfo.setChildren(setSelectedCataloguesUnitBean(CatalogueInfo.getChildren(), returnCatalogueInfo));
                    } else {
                        if (CatalogueInfo.getId().equals(returnCatalogueInfo.getId())) {
                            CatalogueInfo.setSelect(true);
                            mShowingCatalogueInfos.put(CatalogueInfo.getId(), CatalogueInfo);
                        } else {
                            CatalogueInfo.setSelect(false);
                            mShowingCatalogueInfos.remove(CatalogueInfo.getId());
                        }
                    }
                }

            }
        } catch (Exception e) {

        }

        return CatalogueInfoList;
    }

    //查找选中的CataloguesUnitBean
    private CatalogueInfo getSelectedCataloguesUnitBean(List<CatalogueInfo> CatalogueInfoList) {
        try {
            if (CatalogueInfoList != null && CatalogueInfoList.size() > 0) {
                for (int i = 0; i < CatalogueInfoList.size(); i++) {
                    CatalogueInfo CatalogueInfo = CatalogueInfoList.get(i);
                    if (CatalogueInfo.getChildren() != null && CatalogueInfo.getChildren().size() > 0) {
                        CatalogueInfo selectedCataloguesUnitBean = getSelectedCataloguesUnitBean(CatalogueInfo.getChildren());
                        if (selectedCataloguesUnitBean != null) {
                            return selectedCataloguesUnitBean;
                        }
                    } else {
                        if (CatalogueInfo.getSelect()) {
                            return CatalogueInfo;
                        }
                    }
                }

            }
        } catch (Exception e) {

        }

        return null;

    }

    //默认选中第一个可用单元的第一个最后层级
    private List<CatalogueInfo> getLastLevelCataloguesUnitBean(List<CatalogueInfo> CatalogueInfoList) {
        try {
            if (CatalogueInfoList != null && CatalogueInfoList.size() > 0) {
                CatalogueInfo CatalogueInfo = CatalogueInfoList.get(0);
                if (CatalogueInfo.getChildren() != null && CatalogueInfo.getChildren().size() > 0) {
                    CatalogueInfo.setChildren(getLastLevelCataloguesUnitBean(CatalogueInfo.getChildren()));
                } else {
                    CatalogueInfo.setSelect(true);
                    mReadyShowCatalogueInfos.put(CatalogueInfo.getId(), CatalogueInfo);
                }
            }
        } catch (Exception e) {

        }

        return CatalogueInfoList;
    }

    //同步本地选中的记录到刷新回来的数据中
    private void synCataloguesBean(CatelogBean bookDeskCatalogueBean) {
        if (bookDeskCatalogueBean == null) {
            return;
        }
        try {
            mReadyShowCatalogueInfos.clear();
            List<CatalogueInfo> netCatalogues = bookDeskCatalogueBean.getCatalogues();
            if (netCatalogues != null) {
                boolean isSelected = false;
                for (int i = 0; i < netCatalogues.size(); i++) {
                    isSelected = false;
                    if (null != netCatalogues && netCatalogues.size() > 0) {
                        isSelected = synSelectedCatalogueInfo(netCatalogues);
                        //默认选中第一个
                        if (!isSelected && netCatalogues.size() > 0) {
                            getLastLevelCataloguesUnitBean(netCatalogues);
                        }
                    }

                }
            }
            mCataloguesBeanList = netCatalogues;
            mBookDeskCatalogueBean = bookDeskCatalogueBean;
            mShowingCatalogueInfos.clear();
            mShowingCatalogueInfos.putAll(mReadyShowCatalogueInfos);

        } catch (Exception e) {

        }


    }

    private void updateCataloguesBeanFromNet(CatelogBean CatelogBean) {
        synCataloguesBean(CatelogBean);
        updateCataloguesAdapterAndSaveLocal();
    }

    private void updateCataloguesAdapterAndSaveLocal() {
//        mNewBookDeskAdapter.updateCatalogueList(mCataloguesBeanList);
        mNewBookDeskAdapter.updateData(mSubjectBeanList, mCataloguesBeanList);
        // 保存新书桌首页目录数据到本地
        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_DESK_CATALOGUE, (Serializable) mBookDeskCatalogueBean);
    }

    private CatelogBean catelogBean;

    private void loadNetData(final int subjectPosition, final boolean isSwitchReresh, final MaterialBean materialBean, final String mBookId, final String mServiceId) {
        EpaperDao.getInstance().getBookCatalogue(mBookId, "", "", mServiceId, null, new BaseExtCallBack(getContext(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {


            @Override
            public void success(final Object data) {
                try {
                    //后台没数据临时用之前的接口
                    try {
                        if (data != null && data instanceof CatelogBean) {
                            List<CatalogueInfo> netCataloguesBean = ((CatelogBean) data).getCatalogues();
                            boolean isSelected = false;
                            isSelected = synSelectedItemCatalogueInfo(netCataloguesBean);
                            //默认选中第一个
                            getLastLevelCataloguesUnitBean(netCataloguesBean);
                            mCataloguesBeanList.clear();
                            mCataloguesBeanList.addAll(subjectPosition, netCataloguesBean);
                            updateCataloguesAdapterAndSaveLocal();

                            if (isSwitchReresh) {
                                List<MaterialBean> materialBeanList = mSubjectBeanList.get(subjectPosition).getMaterial();
                                for (int i = 0; i < materialBeanList.size(); i++) {
                                    if (materialBean.getVersionId() == materialBeanList.get(i).getVersionId()) {
                                        materialBeanList.get(i).setSelected(true);
                                        if (mVersionIdList != null && mVersionIdList.size() > subjectPosition) {
                                            mVersionIdList.set(subjectPosition, materialBean.getBooksPage().getPackageId());
                                        }
                                    } else {
                                        materialBeanList.get(i).setSelected(false);
                                    }
                                }
                                updateSubjectBeanListAdapterAndSaveLocal();
                            }
                        } else {
                            ToastUtil.INSTANCE.toastCenterError(R.string.server_error);
                        }
                    } catch (Exception e) {

                    }

                } catch (Exception e) {
                    e.getStackTrace();
                }

            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
            }
        });
    }

    //整个页面目录刷新
    private void getBookDeskCatalogue(String mBookId, String mServiceId) {
        if (TextUtils.isEmpty(mBookId)) {
            return;
        }

        EpaperDao.getInstance().getBookCatalogue(mBookId, "", "", mServiceId, null, new BaseExtCallBack(getContext(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {
                //后台没数据临时用之前的接口
                try {
                    if (data != null && data instanceof CatelogBean) {
                        CatelogBean CatelogBean = (CatelogBean) data;
                        updateCataloguesBeanFromNet(CatelogBean);
                    }

                } catch (Exception e) {
                    e.getStackTrace();
                }

            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
            }
        });
    }


    private void initDialogFragment() {
        if (chackGradeBottomDialog == null)
            chackGradeBottomDialog = new ChackGradeBottomDialog(getContext(), R.style.DialogStyleGuide);
        chackGradeBottomDialog.setCanceledOnTouchOutside(true);
        if (catalogBottomDialog == null)
            catalogBottomDialog = new CatalogBottomDialog(getContext(), R.style.DialogStyleGuide);
        catalogBottomDialog.setCanceledOnTouchOutside(true);
    }


    private String getVersionIds(ArrayList<String> versionId) {
        if (versionId != null && versionId.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < versionId.size(); i++) {
                if (i == versionId.size() - 1) {
                    stringBuilder.append(versionId.get(i));
                } else {
                    stringBuilder.append(versionId.get(i) + ",");
                }

            }
            return stringBuilder.toString();
        } else {
            return "";
        }

    }

    private String getBookIds(List<MaterialBean> materialBeanList) {

        try {
            StringBuffer mBookId = new StringBuffer();
            for (MaterialBean materialBean : materialBeanList) {
                if (materialBean.isSelected()) {
                    List<MaterialBean.BooksBean> books = materialBean.getBooks();
                    for (int i = 0; i < books.size(); i++) {
                        MaterialBean.BooksBean booksBean = books.get(i);
                        if (i == books.size() - 1) {
                            mBookId.append(booksBean.getBookId());
                        } else {
                            mBookId.append(booksBean.getBookId() + ",");
                        }
                    }

                }
            }
            return mBookId.toString();
        } catch (Exception e) {

        }

        return "";
    }

    private MaterialBean getMaterialBean(List<MaterialBean> materialBeanList) {

        MaterialBean mMaterialBean = null;
        for (MaterialBean materialBean : materialBeanList) {
            if (materialBean.isSelected()) {
                mMaterialBean = materialBean;
                break;
            }
        }
        return mMaterialBean;
    }

    private void updateSubjectBeanListAdapterAndSaveLocal() {
//		mHandler.sendEmptyMessage(UPDATE_SUBJECT_LIST);
//        mNewBookDeskAdapter.updateSubjectBeanList(mSubjectBeanList);
        mNewBookDeskAdapter.updateData(mSubjectBeanList, mCataloguesBeanList);
        // 保存新书桌首页数据到本地
        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_DESK_HOME_PAGE, (Serializable) mBookDeskBean);
    }

    public void bindData(BookDeskBean bookDeskBean, List<SubjectBean> subjectBeanList, boolean isLocal, List<EpaperInfoGradeNameBean> epaperInfoGradeNameBeans) {
        mBookDeskBean = bookDeskBean;
        mEpaperInfoGradeNameBeans = epaperInfoGradeNameBeans;
        if (isLocal) {
            updateMaterialItemBeansLocal(subjectBeanList);
            EventBus.getDefault().post(new RefreshNewBookDesk(true));
        } else {
            updateMaterialItemBeansFromNet(subjectBeanList);
            if (null != subjectBeanList && subjectBeanList.size() > 0 && null != subjectBeanList.get(0).getMaterial() && subjectBeanList.get(0).getMaterial().size() > 0) {
                if (null != mVersionIdList && mVersionIdList.size() > 0)
                    getBookDeskCatalogue(mVersionIdList.get(0), subjectBeanList.get(0).getMaterial().get(0).getServerId() + "");
            }
        }

    }
}
